package com.xtx.air.bo.feature.impl;

import com.xtx.air.bo.feature.IFeatureBO;
import com.xtx.air.dao.feature.IFeatureDAO;
import com.xtx.air.dataobject.FeatureDO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * User: hanyi
 * Date: 12-2-7
 * Time: 下午10:36
 */
public class FeatureBOImpl implements IFeatureBO{
    private Log logger = LogFactory.getLog(this.getClass());
    private IFeatureDAO featureDAO;

    public void setFeatureDAO(IFeatureDAO featureDAO) {
        this.featureDAO = featureDAO;
    }

    @Override
    public List<FeatureDO> findFeatureByPermissions(List<String> permissions) {
        List<FeatureDO> featureList = featureDAO.findALl();
        List<FeatureDO> filterFeatureList = new ArrayList<FeatureDO>(featureList.size());
        List<FeatureDO> resultFeatureList = new ArrayList<FeatureDO>();
        for(FeatureDO feature : featureList){
            if(feature.getPermissionName() == null || permissions.contains(feature.getPermissionName())){
                filterFeatureList.add(feature);
            }
        }
        for(FeatureDO feature : filterFeatureList){
            if(feature.getPid() == null){
                getChildren(filterFeatureList,feature);
                resultFeatureList.add(feature);
            }
        }
        return resultFeatureList;
    }

    private void getChildren(List<FeatureDO> oriList,FeatureDO parent){
        List<FeatureDO> children = new ArrayList<FeatureDO>();
        for(FeatureDO feature : oriList){
            if(parent.getId().equals(feature.getPid())){
                children.add(feature);
                getChildren(oriList,feature);
            }
        }
        parent.setChildren(children);
    }
}
